<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="房间类型" prop="roomType">
              <el-select v-model="queryParams.roomType" placeholder="请选择房间类型" clearable>
                <el-option
                  v-for="dict in sys_room_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="房间状态" prop="roomStatus">
              <el-select v-model="queryParams.roomStatus" placeholder="请选择房间状态" clearable>
                <el-option
                  v-for="dict in sys_room_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['nursing:roomInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['nursing:roomInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['nursing:roomInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['nursing:roomInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="roomInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="房间ID" align="center" prop="roomId" v-if="false" />
        <el-table-column label="房间号" align="center" prop="roomNumber" />
        <el-table-column label="房间类型" align="center" prop="roomType">
          <template #default="scope">
            <dict-tag :options="sys_room_type" :value="scope.row.roomType"/>
          </template>
        </el-table-column>
        <el-table-column label="房间状态" align="center" prop="roomStatus">
          <template #default="scope">
            <dict-tag :options="sys_room_status" :value="scope.row.roomStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="总床位数" align="center" prop="bedCount" />
        <el-table-column label="可用床位数" align="center" prop="availableBeds">
          <template #default="scope">
            <el-tag :type="scope.row.availableBeds === 0 ? 'danger' : scope.row.availableBeds < scope.row.bedCount * 0.3 ? 'warning' : 'success'">
              {{ scope.row.availableBeds }}/{{ scope.row.bedCount }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleViewBeds(scope.row)" v-hasPermi="['nursing:bedInfo:list']">查看床位</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:roomInfo:edit']"></el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:roomInfo:remove']"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改房间管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="roomInfoFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房间类型" prop="roomType">
          <el-select v-model="form.roomType" placeholder="请选择房间类型" style="width: 100%">
            <el-option
              v-for="dict in sys_room_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间状态" prop="roomStatus" v-if="!isAdd">
          <el-select v-model="form.roomStatus" placeholder="请选择房间状态" style="width: 100%">
            <el-option
              v-for="dict in sys_room_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总床位数" prop="bedCount">
          <el-input-number v-model="form.bedCount" :min="1" :max="10" />
          <div class="form-help-text">设置该房间的总床位数量，创建后会自动生成对应数量的床位</div>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看床位详情对话框 -->
    <el-dialog title="房间床位详情" v-model="bedDialog.visible" width="800px" append-to-body>
      <el-descriptions :title="selectedRoom?.roomNumber + ' 房间信息'" :column="2" border>
        <el-descriptions-item label="房间号">{{ selectedRoom?.roomNumber }}</el-descriptions-item>
        <el-descriptions-item label="房间类型">
          <dict-tag :options="sys_room_type" :value="selectedRoom?.roomType"/>
        </el-descriptions-item>
        <el-descriptions-item label="房间状态">
          <dict-tag :options="sys_room_status" :value="selectedRoom?.roomStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="床位情况">
          <el-tag :type="selectedRoom?.availableBeds === 0 ? 'danger' : selectedRoom?.availableBeds < selectedRoom?.bedCount * 0.3 ? 'warning' : 'success'">
            可用：{{ selectedRoom?.availableBeds }}/{{ selectedRoom?.bedCount }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="center">床位列表</el-divider>
      
      <el-table v-loading="bedLoading" :data="bedList">
        <el-table-column label="床位号" align="center" prop="bedNumber" />
        <el-table-column label="床位状态" align="center" prop="bedStatus">
          <template #default="scope">
            <dict-tag :options="sys_bed_status" :value="scope.row.bedStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="入住老人" align="center" prop="elderName" />
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="goToBedEdit(scope.row)" v-hasPermi="['nursing:bedInfo:edit']">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bedDialog.visible = false">关 闭</el-button>
          <el-button type="primary" @click="goToAddBed">新增床位</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RoomInfo" lang="ts">
import { listRoomInfo, getRoomInfo, delRoomInfo, addRoomInfo, updateRoomInfo } from '@/api/nursing/roomInfo';
import { listBedInfo } from '@/api/nursing/bedInfo';
import { BedInfoVO } from '@/api/nursing/bedInfo/types';
import { RoomInfoVO, RoomInfoQuery, RoomInfoForm } from '@/api/nursing/roomInfo/types';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_room_type, sys_room_status, sys_bed_status } = toRefs<any>(proxy?.useDict('sys_room_type', 'sys_room_status', 'sys_bed_status'));

const router = useRouter();
const roomInfoList = ref<RoomInfoVO[]>([]);
const loading = ref(true);
const buttonLoading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const roomInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 床位详情对话框
const bedDialog = reactive({
  visible: false
});

const selectedRoom = ref(null);
const bedList = ref<BedInfoVO[]>([]);
const bedLoading = ref(false);

const initFormData: RoomInfoForm = {
  roomId: undefined,
  roomNumber: undefined,
  roomType: undefined,
  roomStatus: '可用',
  bedCount: 4,
  availableBeds: 4,
  remarks: undefined
}

const isAdd = ref(false);

const data = reactive<PageData<RoomInfoForm, RoomInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomNumber: undefined,
    roomType: undefined,
    roomStatus: undefined,
    params: {
    }
  },
  rules: {
    roomNumber: [
      { required: true, message: "房间号不能为空", trigger: "blur" }
    ],
    roomType: [
      { required: true, message: "房间类型不能为空", trigger: "change" }
    ],
    roomStatus: [
      { required: true, message: "房间状态不能为空", trigger: "change" }
    ],
    bedCount: [
      { required: true, message: "床位数不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询房间管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRoomInfo(queryParams.value);
  roomInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  roomInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RoomInfoVO[]) => {
  ids.value = selection.map(item => item.roomId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 新增时默认设置房间状态为"可用"
  form.value.roomStatus = '可用';
  isAdd.value = true;
  dialog.visible = true;
  dialog.title = "添加房间管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RoomInfoVO) => {
  reset();
  const _roomId = row?.roomId || ids.value[0];
  const res = await getRoomInfo(_roomId);
  Object.assign(form.value, res.data);
  isAdd.value = false;
  dialog.visible = true;
  dialog.title = "修改房间管理";
}

/** 查看床位按钮操作 */
const handleViewBeds = async (row: RoomInfoVO) => {
  selectedRoom.value = row;
  bedDialog.visible = true;
  bedLoading.value = true;
  
  try {
    const res = await listBedInfo({
      pageNum: 1,
      pageSize: 100,
      roomNumber: row.roomNumber
    });
    bedList.value = res.rows;
  } catch (error) {
    console.error('获取床位列表失败:', error);
    proxy?.$modal.msgError('获取床位列表失败');
  } finally {
    bedLoading.value = false;
  }
}

/** 前往床位编辑页面 */
const goToBedEdit = (bed: BedInfoVO) => {
  bedDialog.visible = false;
  router.push({
    path: '/nursing/bedInfo',
    query: { bedId: bed.bedId }
  });
}

/** 前往新增床位页面 */
const goToAddBed = () => {
  bedDialog.visible = false;
  router.push({
    path: '/nursing/bedInfo',
    query: { roomNumber: selectedRoom.value.roomNumber }
  });
}

/** 提交按钮 */
const submitForm = () => {
  roomInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 设置可用床位数与总床位数相同（对于新增）
        if (isAdd.value) {
          form.value.availableBeds = form.value.bedCount;
          // 设置房间状态为"可用"
          form.value.roomStatus = '可用';
          
          // 在新增时检查房间号是否已存在
          try {
            const checkParams: RoomInfoQuery = {
              roomNumber: form.value.roomNumber,
              pageNum: 1,
              pageSize: 10,
              params: {}
            };
            const checkRes = await listRoomInfo(checkParams);
            if (checkRes && checkRes.rows && checkRes.rows.length > 0) {
              proxy?.$modal.msgError(`房间号"${form.value.roomNumber}"已存在，请更换其他房间号`);
              buttonLoading.value = false;
              return;
            }
          } catch (checkError) {
            console.error("检查房间号唯一性失败:", checkError);
          }
        }
        
        if (form.value.roomId) {
          await updateRoomInfo(form.value);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addRoomInfo(form.value);
          // 显示更详细的成功消息，告知自动生成了床位
          proxy?.$modal.msgSuccess(`房间添加成功，已自动生成${form.value.bedCount}个床位`);
        }
        dialog.visible = false;
        await getList();
      } catch (error: any) {
        console.error("操作失败:", error);
        // 提取后端返回的具体错误信息
        let errorMsg = "操作失败";
        if (error.response && error.response.data && error.response.data.msg) {
          errorMsg = error.response.data.msg;
        } else if (error.message && error.message.includes("房间号已存在")) {
          errorMsg = "房间号已存在，请更换其他房间号";
        }
        proxy?.$modal.msgError(errorMsg);
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RoomInfoVO) => {
  const _roomIds = row?.roomId || ids.value;
  await proxy?.$modal.confirm('是否确认删除房间管理编号为"' + _roomIds + '"的数据项？').finally(() => loading.value = false);
  await delRoomInfo(_roomIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/roomInfo/export', {
    ...queryParams.value
  }, `roomInfo_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.form-help-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  padding-top: 4px;
}
</style>
